package com.syt.cmn.service.impl;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.syt.cmn.listener.DictExcelListener;
import com.syt.cmn.mapper.DictMapper;
import com.syt.cmn.service.DictService;
import com.syt.exception.SYTException;
import com.syt.model.cmn.Dict;
import com.syt.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 组织架构表 服务实现类
 * </p>
 *
 * @author xxxx
 * @since 2023-02-05
 */
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {


    /**
     * 根据dictCode获取下级节点
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        //根据dictCode获取对应id
        Dict dict = this.getDictByDictCode(dictCode);
        //根据id获取子节点
        List<Dict> dictList = this.findChildData(dict.getId());
        return dictList;
    }

    /**
     * 根据dictCode和value查询
     * @param dictCode
     * @param value
     * @return
     */
    @Override
    public String getDictName(String dictCode, String value) {
        //如果dictCode值为空，直接根据value值查询
        if(StringUtils.isEmpty(dictCode)){
            //直接根据value值查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("value", value);
            Dict dict = baseMapper.selectOne(wrapper);
            return dict.getName();
        }else {
            //如果dictCode的值不为空，根据dictCode值和value值查询
            //根据dictCode值查询Dict对象，得到dict的id值
            Dict codeDict = this.getDictByDictCode(dictCode);
            Long parent_id = codeDict.getId();
            //根据parent_id和value查询
            QueryWrapper<Dict> wrapper = new QueryWrapper<>();
            wrapper.eq("parent_id", parent_id);
            wrapper.eq("value", value);
            Dict finalDict = baseMapper.selectOne(wrapper);
            return finalDict.getName();
        }



    }

    private Dict getDictByDictCode(String dictCode){
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        Dict dict = baseMapper.selectOne(wrapper);
        return dict;
    }



    /**
     * 导入字典数据
     *
     * @param file
     * @return
     */
    @Transactional
    @Override
    public void importDictData(MultipartFile file) {

        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictExcelListener(baseMapper)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
            throw new SYTException(e.getMessage(),5001);
        }

    }

    /**
     * 导出数据字典接口
     *
     * @param response
     */
    @Override
    public void exportData(HttpServletResponse response) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        //下载文件名称
        String fileName = "dictionary";
        response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");
        //查询数据库
        List<Dict> list = baseMapper.selectList(null);
        //dict 转换 dictVo
        List<DictEeVo> dictEeVoList = new ArrayList<>();

        for (Dict dict : list) {
            DictEeVo dictEeVo = new DictEeVo();
            //dictEeVo.setId(dict.getId());
            BeanUtils.copyProperties(dict, dictEeVo);
            dictEeVoList.add(dictEeVo);
        }
    }


    /**
     * 根据数据字典id查询子数据列表
     *
     * @param id
     * @return
     */
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        List<Dict> list = baseMapper.selectList(queryWrapper);

        //从List集合每个data对象中设置hashChildren
        for (Dict dict : list) {
            Long dictId = dict.getId();
            boolean isChild = this.isChildren(dictId);
            dict.setHasChildren(isChild);
        }


        return list;
    }

    //判断id下面是否有子节点
    private boolean isChildren(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        return count > 0;
    }
}
